<template>
    <div class="qilin-login">
        <div class="qilin-login-container">
            <div class="qilin-login-container-header">EDGQilin全栈管理系统-Vue3.x版</div>
            <div class="qilin-login-container-box">
                <template v-if="isLogin">
                    <QilinForm v-model:formConfig="loginFormConfig" ref="loginFormRef"
                        @keydown.enter="loginBtn(loginFormRef)" key="loginFormRef"
                    >
                        <template v-slot:extraItem>
                            <div class="qilin-login-content-box-tip" >
                                还没有账号？现在<span @click="isLogin=false">注册</span>|
                                <span @click="forgetPassword()">忘记密码？</span>
                            </div>
                        </template>
                    </QilinForm>
                </template>
                <template v-else>
                    <QilinForm v-model:formConfig="registerFormConfig" ref="registerFormRef"
                        key="registerFormRef" @keydown.enter="registerBtn(registerFormRef)"
                    ></QilinForm>
                </template>
            </div>
        </div>
    </div>
</template>

<script setup>
import jwt_decode from "jwt-decode";
import Qilin from "qilin-utils";
import {setCookie,getCookie,clearCookie} from "@/utils/remember.js";
import {login,register} from "@/api/login/index.js";
import {useRouter} from "vue-router";
import {loginPinia} from "@/store/login/index.js";
const loginPiniaStore=loginPinia();
const router=useRouter();

// 当前是否显示登录表单页面
let isLogin=ref(true);
// 获取登录表单元素
let loginFormRef=ref(null);
// 获取注册表单元素
let registerFormRef=ref(null);
// 确认密码校验事件监听
const validateConfirmPassword=(rule,value,callback)=>{
    if(!value){
        callback("请确认密码");
    }else{
        if(value === registerFormConfig.submitData.password){
            callback();
        }else{
            callback("密码不一致");
        };
    };
};
// 点击登录按钮事件监听
const loginBtn=(formRef)=>{
    formRef.formValidate((valid)=>{
        if(valid){
            // console.log(loginFormConfig.submitData);
            login({...loginFormConfig.submitData}).then((res)=>{
                if(res.code === 1000){
                    if(loginFormConfig.submitData.isRemember.length > 0){ //若选中记住密码
                        setCookie(loginFormConfig.submitData.email,loginFormConfig.submitData.password,15);
                    }else{
                        clearCookie();
                    };
                    ElMessage({
                        message:`欢迎尊敬的${res.data.userInfo.name}用户登录EDGQiLin全栈管理系统！`,
                        type:"success"
                    });
                    if(res.data.userInfo.avatar.includes("//www")){
                        Qilin.Storage.setKeyValueLocalStorage("avatar","moren");
                    }else{
                        Qilin.Storage.setKeyValueLocalStorage("avatar",res.data.userInfo.avatar);
                    };
                    Qilin.Storage.setKeyValueLocalStorage("email",res.data.userInfo.email);
                    Qilin.Storage.setKeyValueLocalStorage("qilinToken",res.data.token);
                    // 解析token，获取token中的信息
                    const userInfo=jwt_decode(res.data.token);
                    loginPiniaStore.setAuthenticated(!Qilin.Common.isEmpty(userInfo));
                    loginPiniaStore.setUserInfo({...userInfo,image:Qilin.Storage.getValueLocalStorage("avatar")});
                    router.push("/index");
                }else{
                    ElMessage({
                        message:res.message || "系统错误",
                        type:"error"
                    });
                };
            });
        };
    });
};
// 点击注册按钮事件监听
const registerBtn=(formRef)=>{
    formRef.formValidate((valid)=>{
        if(valid){
            // console.log(registerFormConfig.submitData);
            register({...registerFormConfig.submitData}).then((res)=>{
                if(res.code === 1000){
                    ElMessage({
                        message:"注册用户成功，请登录！",
                        type:"success"
                    });
                    isLogin.value=true;
                }else{
                    ElMessage({
                        message:res.message || "系统错误",
                        type:"error"
                    });
                };
            });
        };
    });
};
// 点击忘记密码事件监听
const forgetPassword=()=>{
    ElMessage({
        message:"只有管理员才可修改密码",
        type:"info"
    });
};

// 登录表单配置项
const loginFormConfig=reactive({
    itemConfig:[
        {
            labelName:"邮箱",
            dataName:"email",
            type:"input",
            inputType:"text",
            width:24,
            validate:[
                {
                    required:true,
                    message:"请输入邮箱地址",
                    trigger:"blur"
                }
            ]
        },
        {
            labelName:"密码",
            dataName:"password",
            type:"input",
            inputType:"password",
            width:24,
            validate:[
                {
                    required:true,
                    message:"请输入密码",
                    trigger:"blur"
                }
            ]
        },
        {
            dataName:"isRemember",
            hideLabel:true,
            type:"checkbox",
            dataListName:"isRemember",
            width:24,
            className:"qilin-item-isRemember"
        }
    ],
    selectLists:{
        isRemember:[
            {
                label:"记住密码"
            }
        ]
    },
    buttonConfigClassName:"qilin-button-item",
    buttonConfig:[
        {
            btnName:"登录",
            type:"primary",
            size:"default",
            class:"qilin-button",
            formRefName:loginFormRef,
            click:loginBtn
        }
    ],
    submitData:{
        email:"",
        password:"",
        isRemember:[]
    }
});
// 注册表单配置项
const registerFormConfig=reactive({
    elFormConfig:{
        labelWidth:"90"
    },
    itemConfig:[
        {
            labelName:"用户名",
            dataName:"name",
            type:"input",
            inputType:"text",
            width:24,
            validate:[
                {
                    required:true,
                    message:"请输入用户名",
                    trigger:"blur"
                },
                {
                    min:4,
                    max:12,
                    message:"用户名长度在4~12个字符之间",
                    trigger:"blur"
                }
            ]
        },
        {
            labelName:"邮箱",
            dataName:"email",
            type:"input",
            inputType:"text",
            width:24,
            validate:[
                {
                    type:"email",
                    required:true,
                    message:"邮箱格式不正确",
                    trigger:["blur","change"]
                }
            ]
        },
        {
            labelName:"密码",
            dataName:"password",
            type:"input",
            inputType:"password",
            showPassword:true,
            width:24,
            validate:[
                {
                    required:true,
                    message:"请输入密码",
                    trigger:"blur"
                }
            ]
        },
        {
            labelName:"确认密码",
            dataName:"confirmPassword",
            type:"input",
            inputType:"password",
            showPassword:true,
            width:24,
            validate:[
                {
                    required:true,
                    trigger:"blur",
                    validator:validateConfirmPassword
                }
            ]
        }
    ],
    buttonConfig:[
        {
            btnName:"注册",
            type:"primary",
            size:"default",
            style:"flex:1;",
            formRefName:registerFormRef,
            click:registerBtn
        },
        {
            btnName:"返回登录",
            type:"default",
            size:"default",
            click:()=>{
                registerFormRef.value.formResetFields();
                isLogin.value=true;
            }
        }
    ],
    submitData:{
        name:"",
        email:"",
        password:"",
        confirmPassword:"",
        identify:""
    }
});

// 生命周期逻辑区域
// 初始化判断是否之前选中了记住密码功能
const info=getCookie();
if(info){
    if(info.username && info.username?.length > 0){
        loginFormConfig.submitData.email=info.username;
        loginFormConfig.submitData.password=info.password;
        loginFormConfig.submitData.isRemember=["记住密码"];
    };
};

</script>

<style lang="scss" scoped>
.qilin-login{
    position:relative;
    @include QilinWidthHeight();
    @include QilinBgImage("@/assets/images/pc1.jpeg");
    >.qilin-login-container{
        width:420px;
        transform:translate(-50%,-50%);
        @include QilinPosition(absolute,40%,50%);
        >.qilin-login-container-header{
            color:$primary-text-color;
            width:100%;
            font-size:$huge-text-size;
            font-weight:bolder;
            text-align:center;
            letter-spacing:1px;
            padding:20px;
        }
        >.qilin-login-container-box{
            background-color:#fff;
            border-radius:5px;
            padding:20px;
            :deep(.el-form){
                padding:20px 20px 0 20px;
                >.qilin-item-isRemember{
                    >.el-form-item__content{
                        justify-content: flex-end;
                    }
                }
                >.qilin-button-item{
                    >.el-form-item__content{
                        margin-left:120px !important;
                        >.qilin-button{
                            width:50%;
                        }
                    }
                }
            }
            .qilin-login-content-box-tip{
                font-size:$small-text-size;
                padding:0 20px 0 20px;
                text-align:right;
                color:$invalid-color;
                >span:first-child{
                    color:$primary-text-color;
                    cursor:pointer;
                    font-weight:bolder;
                    text-decoration:underline;
                    margin-right:10px;
                }
                >span:last-of-type{
                    margin-left:5px;
                    color:$primary-text-color;
                    cursor:pointer;
                    font-weight:bolder;
                }
            }
        }
    }
}
</style>
